/**
 * @apiDefine ErrorResponse
 * @apiError (请求错误) {String} err_message 错误信息描述
 */

/**
 * @apiVersion 1.0.0
 * @apiGroup 订单
 * @api {GET} api/order/list 订单列表
 * @apiName api/order/list
 * @apiExample {js} axios 例子:
 *  axios.get('http://39.105.38.34:8080/api/order/list', {
 *    params: {
 *      storeid: 23, // 店铺 ID
 *      size: 10,
 *      page: 1,
 *    }
 *  });
 * @apiHeader {String} authorization 用户登录或注册成功时返回的 token
 * @apiParam {Number} [page=1] 分页的页数
 * @apiParam {Number} [size=10] 每页的条数
 * @apiSuccess (请求成功) {Array} orderlist 店铺列表
 * @apiuse  ErrorResponse
 */

const { query } = require('../../helper/db');
const { door, ok } = require('../../helper/util');


module.exports = async ctx => {
  var token = ctx.headers.authorization;
  var user = await door(token);
  var params = ctx.query;
  var sql = ['select * from order where 1 = 1'];
  var values = [];
  var size = params.size ? params.size : 10;
  var page = params.page ? params.page : 1;
  var end = size * page;

  sql.push('order by id desc limit ?, ?');

  values.push(end - 10);
  values.push(end);

  var orderlist = await query(sql.join(' '), values);

  if (!orderlist.length) return ctx.body = ok({ orderlist: [] });

  var orderIDs = orderlist.map(item => item.id);
  var orderAddressList = await query('select * from orderAddress where orderid in (?)', [orderIDs]);
  var orderProductList = await query('select * from orderProduct where orderid in (?)', [orderIDs]);
  var orderProductOptionList = await query('select * from orderProductOption where orderid in (?)', [orderIDs]);

  orderlist.forEach(order => {
    order.productlist = [];
    order.address = {};
    
    orderAddressList.forEach(orderAddress => {
      if (order.id !== orderAddress.orderid) return;
      order.address = orderAddress;
    })

    orderProductList.forEach(orderProduct => {
      if (order.id !== orderProduct.orderid) return;

      order.productlist.push(orderProduct);
    });
  });

  orderlist.forEach(order => {
    order.productlist.forEach(orderProduct => {
      orderProduct.optionlist = [];

      orderProductOptionList.forEach(orderProductOption => {
        if (order.id !== orderProductOption.orderid) return;
        if (orderProduct.productid !== orderProductOption.productid) return;

        orderProduct.optionlist.push(orderProductOption);
      })
    })
  })

  ctx.body = ok({ orderlist });
}

